import { Clock } from '$lib/clock';
import { Creature, Description, Glyph, Interesting, AI, Size, type Entity } from '$lib/components';
import { random } from '$lib/random';
import { defineComponent, hasComponent, type IWorld } from '$lib/ecs';
import { registerAI } from '$lib/simulate';
import { Move3Action } from '$lib/walk3';
import { Heart } from '$lib/content/heart';

export const Crow = defineComponent('Crow', {});

export const crowTemlate = [
  [Crow],
  [Creature],
  [Glyph, {
    glyph: 'w',
    color: '#222',
  }],
  [Description, {
    summary: "crow",
    description: "Common medium-sized bird. Some consider it beautiful and there's a certain merit to that. Could be dangerous if starved, luckily you never met one that hungry.",
  }],
  [Interesting],
  [Size, {
    size: 4,
  }],
  [Clock],
  [Heart, {
    heartbeat: 5,
    elapsed: 0,
  }],
  [AI],
];

const crowCanPass = (world, es) => {
  const hasCreature = es.some((e) => hasComponent(world, Creature, e));
  if (hasCreature)
    return false;
  return true;
};

export const CrowMove = (dx, dy, dz) => (world, e) => {
  const delay = Heart.heartbeat[e];
  return Move3Action(crowCanPass)(dx, dy, dz, delay)(world, e);
};

registerAI({
  target: Crow,
  action: (world: IWorld, e: Entity) => {
    const r = Math.floor(random()*8);
    const x = (r < 3) - (r > 4);
    const y = [0, 3, 5].includes(r) - [2, 4, 7].includes(r);
    return CrowMove(x, y, 0)(world, e);
  },
});
